//
//  TTMyAddressViewController.m
//  TaoTuo
//
//  Created by 周晨晔 on 2019/9/23.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTMyAddressViewController.h"
#import "TTMyAddressViewCell.h"
#import "TTAddNewAddressViewController.h"

static NSString *cellID = @"my_address_cellID";

@interface TTMyAddressViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, copy) void(^selectBlock)(TTAddressModel *model);

@property (nonatomic, assign) BOOL isChangeAddress;

@property (nonatomic, strong) NSIndexPath *lastIndexPath;

@property (nonatomic, strong) TTAddressModel *selectModel;

@end

@implementation TTMyAddressViewController

- (instancetype)initWithSelectBlock:(void (^)(TTAddressModel * _Nonnull))selectBlock isChangeAddress:(BOOL)isChangeAddress
{
    if (self == [super init]) {
        self.selectBlock = selectBlock;
        self.isChangeAddress = isChangeAddress;
    }
    return self;
}

- (instancetype)initWithSelectBlock:(void (^)(TTAddressModel * _Nonnull))selectBlock
{
    if (self == [super init]) {
        self.selectBlock = selectBlock;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIButton *btn = [UIButton createButtonWithTitle:@"新增地址" titleColor:kMainColor titleFont:[UIFont systemFontOfSize:15] backgroundColor:nil target:self action:@selector(addNewAddress)];
    btn.frame = CGRectMake(0, 0, 50, 44);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    self.title = @"我的收货地址";
    @weakify(self)
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        self.page = 1;
        [self getAddressListData];
    }];
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        self.page++;
        [self getAddressListData];
    }];
    
    
    // 添加新地址之后
    [[TTLoginSingle sharedSingle].addAddressSuccessSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        [self.tableView.mj_header beginRefreshing];
    }];
    
    
    [self addBottomView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTMyAddressViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    [cell setModel:self.dataArray[indexPath.row] isChangeAddress:self.isChangeAddress];
    @weakify(self)
    cell.selectBlock = ^(TTMyAddressViewCell * _Nonnull tCell, TTAddressModel * _Nonnull model) {
        @strongify(self)
        NSIndexPath *inp = [tableView indexPathForCell:tCell];
        [self handelClickCellOrBtnWithIndexPath:inp];
    };
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    @weakify(self)
    return [tableView fd_heightForCellWithIdentifier:cellID cacheByIndexPath:indexPath configuration:^(TTMyAddressViewCell *cell) {
        @strongify(self)
        [cell setModel:self.dataArray[indexPath.row] isChangeAddress:self.isChangeAddress];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isChangeAddress) {
        
        [self handelClickCellOrBtnWithIndexPath:indexPath];
        
        return;
    }
    
    
    TTAddressModel *model = self.dataArray[indexPath.row];
    
    if (self.selectBlock) {
        self.selectBlock(model);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

// 获取地址列表
- (void)getAddressListData
{
    NSDictionary *dic = @{
                          @"param.pageIndex" : @(self.page),
                          @"param.pageSize" : @(10)
                          };
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getAddressList_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (self.page == 1) {
            [self.dataArray removeAllObjects];
        }
        
        NSArray *arr = responseObject;
        for (NSDictionary *dic in arr) {
            TTAddressModel *model = [TTAddressModel modelWithJSON:dic];
            [self.dataArray addObject:model];
        }
        
        [self.tableView.mj_header endRefreshing];
        
        if (arr.count < 10) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        
        [self.tableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    } showLoadingInView:self.view];
}

// 添加新地址
- (void)addNewAddress
{
    TTAddNewAddressViewController *newVC = [[TTAddNewAddressViewController alloc] init];
    [self.navigationController pushViewController:newVC animated:YES];
}

- (void)handelClickCellOrBtnWithIndexPath:(NSIndexPath *)indexPath
{
    if (self.lastIndexPath) {
        TTAddressModel *addrModel = self.dataArray[self.lastIndexPath.row];
        addrModel.isSelect = NO;
    }
    
    
    TTAddressModel *model = self.dataArray[indexPath.row];
    model.isSelect = YES;
    
    self.lastIndexPath = indexPath;
    
    self.selectModel = model;
    
    [self.tableView reloadData];
}

- (void)confirmExchangeClick
{
    if (self.selectBlock) {
        self.selectBlock(self.selectModel);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addBottomView
{
    if (self.isChangeAddress) {
        
        UIButton *bottomBtn = [UIButton createButtonWithTitle:@"确认更换" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:18] backgroundColor:kMainColor target:self action:@selector(confirmExchangeClick)];
        [self.view addSubview:bottomBtn];
        [bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottomLayoutGuide);
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(45);
        }];
        
    }
}


- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.emptyImageName = @"nodata";
        _tableView.emptyTitel = @"暂无收货地址";
        _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TTMyAddressViewCell class]) bundle:nil] forCellReuseIdentifier:cellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
        }];
    }
    return _tableView;
}



- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


@end
